package com.qdlc.p2p.manage.action.additional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.EnjoyGoodsService;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.AdditionalFlowUploadType;
import com.qdlc.p2p.common.exception.BorrowException;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.MessageUtil;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.AdditionalFlowUpload;
import com.qdlc.p2p.dal.dto.EnjoyGoods;
import com.qdlc.p2p.dal.dto.EnjoyUpload;
import com.qdlc.p2p.dal.model.EnjoyGoodsModel;
import com.qdlc.p2p.manage.common.menu.Prefecture;

/**
 * 商品管理Action
 * Created by D on 2016/1/20.
 */
public class ManageEnjoyGoodsAction extends BaseAction<EnjoyGoodsModel> implements ModelDriven<EnjoyGoodsModel> {

    @Resource
    private EnjoyGoodsService enjoyGoodsService;

    private Map<String, Object> data;

    private long[] delIds; // 删除的图片ID

    private final Map<Integer,Object> prefecture= Prefecture.prefecture;

    @Action("/modules/additional/enjoyGoods/manage")
    public String manage(){
        return "manage";
    }

    /**
     * 获取列表信息
     * @throws IOException
     */
    @Action("/modules/additional/enjoyGoods/listJson")
    public void listJson() throws IOException{
        data = new HashMap<String, Object>();
        PageDataList<EnjoyGoods> pagaDataList = enjoyGoodsService.findByModel(model);
        int total = pagaDataList.getPage().getTotal();
        data.put("total", total);
        data.put("rows", pagaDataList.getList());
        printJson(getStringOfJpaObj(data));
    }

    /**
     * 添加
     * @return
     */
    @Action("/modules/additional/enjoyGoods/append")
    public String append(){
        request.setAttribute("prefectureMap", prefecture);
        return "append";
    }

    /**
     * 添加
     * @throws Exception
     */
    @Action("/modules/additional/enjoyGoods/doAppend")
    public void doAppend() throws Exception {
        data = new HashMap<String, Object>();
        model.validModelData();
        EnjoyGoods enjoyGoods = model.prototypeForAppend();
        try {
            model.validModelData();

            List<EnjoyUpload> list = new ArrayList<EnjoyUpload>();

            String[] picPaths = request.getParameterValues("picPath");
            if (picPaths == null) {
                throw new BorrowException("商品介绍图片不能为空", BusinessException.TYPE_JSON);
            }
            for (String picPath : picPaths) {
                EnjoyUpload eu = new EnjoyUpload();
                eu.setPicPath(picPath);
                eu.setType(2);
                list.add(eu);
            }

            String[] thumbnailPaths = request.getParameterValues("thumbnailPicPath");
            if (null != thumbnailPaths
                    && thumbnailPaths.length > 0) {
                for (String picPath : thumbnailPaths) {
                    EnjoyUpload eu = new EnjoyUpload();
                    eu.setPicPath(picPath);
                    eu.setType(1);
                    list.add(eu);
                }
            }

            enjoyGoodsService.save(enjoyGoods,list);
            printResult("添加成功", true);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        data.put("result", "true");
        data.put("msg", MessageUtil.getMessage("MF102100002"));
        printJson(getStringOfJpaObj(data));
    }

    /**
     * 修改
     * @return
     */
    @Action("/modules/additional/enjoyGoods/modify")
    public String modify() {
        List<EnjoyUpload> picList = enjoyGoodsService.findPicByGoodsId(model.getId());
        request.setAttribute("picList", picList);
        EnjoyGoods enjoyGoods = enjoyGoodsService.findById(model.getId());
        request.setAttribute("enablePosition", enjoyGoodsService.enablePosition(enjoyGoods.getPrefecture(),model.getId()));
        request.setAttribute("isBorrow", enjoyGoodsService.isBorrow(model.getId()));
        request.setAttribute("enjoyGoods", enjoyGoods);
        request.setAttribute("prefectureMap",prefecture);
        return "modify";
    }

    /**
     * 修改
     * @return
     */
    @Action("/modules/additional/enjoyGoods/doModify")
    public void doModify() throws Exception {
        data = new HashMap<String, Object>();
        model.validModelData();
        EnjoyGoods oldGoods=enjoyGoodsService.findById(model.getId());
        EnjoyGoods enjoyGoods = model.prototype();
        enjoyGoods.setId(oldGoods.getId());
        enjoyGoods.setAddTime(oldGoods.getAddTime());
        enjoyGoods.setAddIp(oldGoods.getAddIp());
        enjoyGoods.setSendout(oldGoods.getSendout());
        enjoyGoods.setStatus(oldGoods.getStatus());
        List<EnjoyUpload> list = new ArrayList<EnjoyUpload>();
        String[] picPaths = request.getParameterValues("picPath");
        if (picPaths != null) {
            for (String picPath : picPaths) {
                EnjoyUpload eu = new EnjoyUpload();
                eu.setGoodsId(model.getId());
                eu.setPicPath(picPath);
                eu.setType(2);
                list.add(eu);
            }
        }
        String[] thumbnailPaths = request.getParameterValues("thumbnailPath");
        if (thumbnailPaths != null) {
            for (String picPath : thumbnailPaths) {
                EnjoyUpload eu = new EnjoyUpload();
                eu.setGoodsId(model.getId());
                eu.setPicPath(picPath);
                eu.setType(1);
                list.add(eu);
            }
        }
        enjoyGoodsService.update(enjoyGoods,list,delIds);
        data.put("result", "true");
        data.put("msg", MessageUtil.getMessage("MF102100003"));
        printJson(getStringOfJpaObj(data));
    }

    /**
     * 查看商品
     * @return
     */
    @Action("/modules/additional/enjoyGoods/detail")
    public String detail() {
        List<EnjoyUpload> picList = enjoyGoodsService.findPicByGoodsId(model.getId());
        request.setAttribute("picList", picList);
        EnjoyGoods enjoyGoods = enjoyGoodsService.findById(model.getId());
        request.setAttribute("enjoyGoods", enjoyGoods);
        request.setAttribute("enjoyPrefecture",prefecture.get(enjoyGoods.getPrefecture()));
        return "detail";
    }


    /**
     * 获取有库存的商品
     * @throws IOException
     */
    @Action("/modules/additional/enjoyGoods/enjoyGoodsJson")
    public void enjoyGoodsListJson() throws IOException {
        List<EnjoyGoods> list = enjoyGoodsService.findUsableEnjoyGoods();
        JSONArray jsonArray = new JSONArray();//new一个json数组
        if (!list.isEmpty() && list.size() > 0) {
            for (EnjoyGoods entity : list) {
                JSONObject obj = new JSONObject();
                obj.put("goodsId", entity.getId());
                obj.put("goodsName", entity.getName());
                jsonArray.add(obj);//循环new jsonObject
            }
        }
        printJson(jsonArray.toString());
    }

    /**
     * 通过专区Id获取还未占据的位置
     */
    @Action("/modules/additional/enjoyGoods/enablePosition")
    public void enablePosition() throws IOException{
        data=new HashMap<String, Object>();
        if(request.getParameter("enjoyGoodsId")!=null)
            data.put("position",enjoyGoodsService.enablePosition(paramInt("prefecture"),paramLong("enjoyGoodsId")));
        else
            data.put("position",enjoyGoodsService.enablePosition(paramInt("prefecture")));
        printWebJson(getStringOfJpaObj(data));
    }

    public long[] getDelIds() {
        return delIds;
    }

    public void setDelIds(long[] delIds) {
        this.delIds = delIds;
    }
}
